package orders

import (
	"context"
	"github.com/cloudwego/hertz/pkg/common/hlog"
	"gorm.io/gen"
	"gorm.io/gen/field"
	"mall_admin_api/biz/dal"
	"mall_admin_api/biz/model"
	"mall_admin_api/biz/model/admin_express"
	"mall_admin_api/biz/pack"
)

func (c *Orders) GetExpressList(ctx context.Context, req *admin_express.GetExpressListRequest, page, size int) ([]*admin_express.Express, int64, error) {
	list, total, err := c.dao.ExpressDAO.GetListWithTotal(ctx, &dal.ExpressListParams{
		Condition: nil,
		Page:      page,
		Size:      size,
	})
	if err != nil {
		hlog.CtxErrorf(ctx, "GetExpressList err: %v", err)
		return nil, 0, err
	}
	return pack.GetExpressList(list), total, nil
}

func (c *Orders) GetExpressSelectList(ctx context.Context, req *admin_express.GetExpressSelectListRequest) ([]*admin_express.Express, error) {
	list, err := c.dao.ExpressDAO.GetExpressList(ctx, nil, 0, 0)
	if err != nil {
		hlog.CtxErrorf(ctx, "GetExpressList err: %v", err)
		return nil, err
	}
	return pack.GetExpressList(list), nil
}

func (c *Orders) UpdateExpress(ctx context.Context, req *admin_express.UpdateExpressRequest) error {
	var fields []field.AssignExpr
	fields = append(fields, dal.Express.UpdatedBy.Value(c.commonInfo.GetAdministratorInfo().Nickname),
		dal.Express.Name.Value(req.GetName()),
		dal.Express.Code.Value(req.GetCode()),
		dal.Express.Sort.Value(req.GetSort()),
	)
	if err := c.dao.ExpressDAO.UpdateExpress(ctx, []gen.Condition{dal.Express.ID.Eq(req.ID)}, fields); err != nil {
		hlog.CtxErrorf(ctx, "UpdateExpress err: %v", err)
		return err
	}
	return nil
}

func (c *Orders) ExpressInfo(ctx context.Context, req *admin_express.GetExpressInfoRequest) (*admin_express.Express, error) {
	//info, err := dal.GetExpressList()ctx, req.GetID())
	//if err != nil {
	//	hlog.CtxErrorf(ctx, "Info err: %v", err)
	//	return nil, err
	//}
	return pack.Express(nil), nil
}

func (c *Orders) DeleteExpress(ctx context.Context, req *admin_express.DeleteExpressRequest) error {
	if err := c.dao.ExpressDAO.DeleteExpress(ctx, []gen.Condition{dal.Express.ID.In(req.IDs...)}); err != nil {
		hlog.CtxErrorf(ctx, "DeleteExpress err: %v", err)
		return err
	}
	return nil
}

func (c *Orders) CreateExpress(ctx context.Context, req *admin_express.CreateExpressRequest) error {
	data := &model.Express{
		Code:      req.Code,
		Name:      req.Name,
		Sort:      req.Sort,
		BizID:     c.commonInfo.GetBizInfo().ID,
		CreatedBy: c.commonInfo.GetAdministratorInfo().Nickname,
	}
	if _, err := c.dao.ExpressDAO.CreateExpress(ctx, data); err != nil {
		hlog.CtxErrorf(ctx, "CreateExpress err: %v", err)
		return err
	}
	return nil
}
